import pygame
import sys
import random
import os

# 初始化 Pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 400, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("跳一跳小游戏")

# 颜色定义
BACKGROUND = (230, 230, 250)
PLAYER_COLOR = (70, 130, 180)
PLATFORM_COLOR = (143, 188, 143)
TEXT_COLOR = (50, 50, 50)
GAME_OVER_BG = (255, 99, 71)
START_SCREEN_BG = (176, 224, 230)
VICTORY_BG = (50, 205, 50)

# 加载中文字体
def get_chinese_font(size):
    # 尝试加载系统中可能存在的字体
    font_names = [
        'SimHei', 'Microsoft YaHei', 'SimSun', 'KaiTi', 'FangSong', 
        'STHeiti', 'STKaiti', 'STSong', 'STFangsong'
    ]
    
    for font_name in font_names:
        try:
            font = pygame.font.SysFont(font_name, size)
            # 测试字体是否能渲染中文
            test_surface = font.render("测试", True, (0, 0, 0))
            if test_surface.get_width() > 0:
                return font
        except:
            continue
    
    # 如果系统字体都不可用，尝试使用默认字体
    try:
        return pygame.font.Font(None, size)
    except:
        return pygame.font.SysFont(None, size)

# 玩家设置
player_size = 30
player_x = WIDTH // 2 - player_size // 2
player_y = HEIGHT - 150
player_velocity_x = 0  # 水平速度
player_velocity_y = 0  # 垂直速度
player_speed = 5       # 水平移动速度
gravity = 0.5
jump_strength = -14
is_jumping = False

# 平台设置
platforms = []
platform_width = 70
platform_height = 15
platform_gap = 100
platform_speed = 2

# 游戏状态
score = 0
game_over = False
game_started = False  # 游戏是否已经开始
game_won = False      # 游戏是否胜利
font = get_chinese_font(36)
small_font = get_chinese_font(24)
title_font = get_chinese_font(48)

# 初始化平台
def init_platforms():
    platforms.clear()
    # 创建一个起始平台，玩家站在上面
    start_platform_x = WIDTH // 2 - platform_width // 2
    start_platform_y = HEIGHT - 100
    platforms.append(pygame.Rect(start_platform_x, start_platform_y, platform_width, platform_height))
    
    # 创建其他平台
    y_pos = start_platform_y - platform_gap
    while y_pos > 0:
        x_pos = random.randint(0, WIDTH - platform_width)
        platforms.append(pygame.Rect(x_pos, y_pos, platform_width, platform_height))
        y_pos -= platform_gap

# 绘制玩家
def draw_player():
    pygame.draw.rect(screen, PLAYER_COLOR, (player_x, player_y, player_size, player_size))
    pygame.draw.rect(screen, (255, 255, 255), (player_x, player_y, player_size, player_size), 2)

# 绘制平台
def draw_platforms():
    for platform in platforms:
        pygame.draw.rect(screen, PLATFORM_COLOR, platform)
        pygame.draw.rect(screen, (255, 255, 255), platform, 1)

# 显示分数
def show_score():
    score_text = font.render(f"分数: {score}/100", True, TEXT_COLOR)
    screen.blit(score_text, (10, 10))

# 显示游戏说明
def show_instructions():
    instruction1 = small_font.render("空格键: 跳跃", True, TEXT_COLOR)
    instruction2 = small_font.render("A/←: 左移  D/→: 右移", True, TEXT_COLOR)
    screen.blit(instruction1, (WIDTH - instruction1.get_width() - 10, 10))
    screen.blit(instruction2, (WIDTH - instruction2.get_width() - 10, 40))

# 显示游戏结束画面
def show_game_over():
    overlay = pygame.Surface((WIDTH, HEIGHT))
    overlay.set_alpha(200)
    overlay.fill(GAME_OVER_BG)
    screen.blit(overlay, (0, 0))
    
    game_over_text = font.render("游戏结束!", True, (255, 255, 255))
    score_text = font.render(f"最终分数: {score}", True, (255, 255, 255))
    restart_text = font.render("按 R 重新开始", True, (255, 255, 255))
    
    screen.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, HEIGHT // 2 - 60))
    screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2 - 20))
    screen.blit(restart_text, (WIDTH // 2 - restart_text.get_width() // 2, HEIGHT // 2 + 20))

# 显示胜利画面
def show_victory():
    overlay = pygame.Surface((WIDTH, HEIGHT))
    overlay.set_alpha(200)
    overlay.fill(VICTORY_BG)
    screen.blit(overlay, (0, 0))
    
    victory_text = font.render("恭喜你赢了!", True, (255, 255, 255))
    score_text = font.render(f"最终分数: {score}", True, (255, 255, 255))
    restart_text = font.render("按 R 重新开始", True, (255, 255, 255))
    
    screen.blit(victory_text, (WIDTH // 2 - victory_text.get_width() // 2, HEIGHT // 2 - 60))
    screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2 - 20))
    screen.blit(restart_text, (WIDTH // 2 - restart_text.get_width() // 2, HEIGHT // 2 + 20))

# 显示开始界面
def show_start_screen():
    screen.fill(START_SCREEN_BG)
    
    title_text = title_font.render("跳一跳", True, (25, 25, 112))
    start_text = font.render("按空格键开始游戏", True, (25, 25, 112))
    instruction1 = small_font.render("空格键: 跳跃", True, (25, 25, 112))
    instruction2 = small_font.render("A/←: 左移  D/→: 右移", True, (25, 25, 112))
    goal_text = small_font.render("目标: 达到100分", True, (25, 25, 112))
    
    screen.blit(title_text, (WIDTH // 2 - title_text.get_width() // 2, HEIGHT // 4))
    screen.blit(start_text, (WIDTH // 2 - start_text.get_width() // 2, HEIGHT // 2))
    screen.blit(instruction1, (WIDTH // 2 - instruction1.get_width() // 2, HEIGHT // 2 + 50))
    screen.blit(instruction2, (WIDTH // 2 - instruction2.get_width() // 2, HEIGHT // 2 + 80))
    screen.blit(goal_text, (WIDTH // 2 - goal_text.get_width() // 2, HEIGHT // 2 + 120))

# 初始化游戏
init_platforms()
# 将玩家放在起始平台上
start_platform = platforms[0]
player_x = start_platform.x + start_platform.width // 2 - player_size // 2
player_y = start_platform.y - player_size

# 游戏主循环
clock = pygame.time.Clock()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and not game_started:
                # 开始游戏
                game_started = True
            elif event.key == pygame.K_SPACE and not is_jumping and game_started and not game_over and not game_won:
                player_velocity_y = jump_strength
                is_jumping = True
            if event.key == pygame.K_r and (game_over or game_won):
                # 重置游戏
                game_over = False
                game_won = False
                game_started = False
                score = 0
                init_platforms()
                # 将玩家放在起始平台上
                start_platform = platforms[0]
                player_x = start_platform.x + start_platform.width // 2 - player_size // 2
                player_y = start_platform.y - player_size
                player_velocity_x = 0
                player_velocity_y = 0
                is_jumping = False
    
    if game_started and not game_over and not game_won:
        # 处理水平移动
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            player_velocity_x = -player_speed
        elif keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            player_velocity_x = player_speed
        else:
            player_velocity_x = 0
        
        # 更新玩家位置
        player_velocity_y += gravity
        player_x += player_velocity_x
        player_y += player_velocity_y
        
        # 确保玩家不会移出屏幕左右边界
        if player_x < 0:
            player_x = 0
        elif player_x > WIDTH - player_size:
            player_x = WIDTH - player_size
        
        # 检测与平台的碰撞
        player_rect = pygame.Rect(player_x, player_y, player_size, player_size)
        on_platform = False
        
        # 先移动平台
        for platform in platforms:
            platform.y += platform_speed
        
        # 然后检测碰撞
        for platform in platforms:
            # 如果玩家站在平台上
            if (player_velocity_y >= 0 and  # 只在下落时检测
                player_rect.bottom >= platform.top and 
                player_rect.bottom <= platform.top + 15 and  # 增加检测范围
                player_rect.right > platform.left + 5 and  # 减少边缘检测
                player_rect.left < platform.right - 5):
                
                # 精确放置玩家在平台上
                player_y = platform.top - player_size
                player_velocity_y = 0
                is_jumping = False
                on_platform = True
                break  # 只处理一个平台的碰撞
        
        # 移除屏幕底部的平台并添加新平台
        if platforms and platforms[0].top > HEIGHT:
            platforms.pop(0)
            x_pos = random.randint(0, WIDTH - platform_width)
            platforms.append(pygame.Rect(x_pos, -platform_height, platform_width, platform_height))
            score += 1
            
            # 检查是否达到胜利条件
            if score >= 100:
                game_won = True
        
        # 检查游戏结束条件
        if player_y > HEIGHT:
            game_over = True
    
    # 绘制背景
    screen.fill(BACKGROUND)
    
    # 绘制平台
    draw_platforms()
    
    # 绘制玩家
    draw_player()
    
    # 显示分数和说明
    if game_started:
        show_score()
        show_instructions()
    
    # 如果游戏结束，显示游戏结束画面
    if game_over:
        show_game_over()
    
    # 如果游戏胜利，显示胜利画面
    if game_won:
        show_victory()
    
    # 如果游戏未开始，显示开始界面
    if not game_started and not game_over and not game_won:
        show_start_screen()
    
    # 更新屏幕
    pygame.display.flip()
    
    # 控制游戏帧率
    clock.tick(60)
    
    